package com.tgjs.sphoto.activity;

import android.annotation.SuppressLint;
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.tgjs.sphoto.constant.ConstantValues;
import com.tgjs.sphoto.entity.PhotoDetailsDTO;
import com.tgjs.sphoto.request.Api;
import com.tgjs.sphoto.utils.DownloadUtil;
import com.tgjs.sphoto.utils.GlideCircleTransform;
import com.tgjs.sphoto.utils.ShareUtils;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.io.IOException;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

public class PhotoDetailActivity extends BaseActivity implements View.OnClickListener {
	@BindView(R.id.imageView)
	ImageView imageView;
	@BindView(R.id.tv_toolbar)
	TextView tvToolbar;
	@BindView(R.id.toolbar)
	Toolbar toolbar;
	@BindView(R.id.collapsing)
	CollapsingToolbarLayout collapsing;
	@BindView(R.id.appbar)
	AppBarLayout appbar;
	@BindView(R.id.img_detailProfile)
	ImageView imgDetailProfile;
	@BindView(R.id.tv_detailUserName)
	TextView tvDetailUserName;
	@BindView(R.id.tv_detailResolution)
	TextView tvDetailResolution;
	@BindView(R.id.tv_shutter)
	TextView tvShutter;
	@BindView(R.id.tv_aperture)
	TextView tvAperture;
	@BindView(R.id.tv_focus)
	TextView tvFocus;
	@BindView(R.id.tv_equipment)
	TextView tvEquipment;
	@BindView(R.id.tv_place)
	TextView tvPlace;
	@BindView(R.id.tv_speed)
	TextView tvSpeed;
	private String ProfileImage;
	private String Background;
	private String UserName;
	private String PId;
	private Bitmap bitmap;
	private Bitmap mBitmap;

	@Override
	protected int getContentView() {
		return R.layout.activity_user_detail;
	}

	@Override
	protected void initViews() {
		mApi = new Api(handler, PhotoDetailActivity.this);
		PId = getIntent().getStringExtra("PId");
		ProfileImage = getIntent().getStringExtra("ProfileImage");
		Background = getIntent().getStringExtra("Background");
		UserName = getIntent().getStringExtra("UserName");
		Random random = new Random();
		int r = random.nextInt(256);
		int g = random.nextInt(256);
		int b = random.nextInt(256);
		imageView.setBackgroundColor(Color.rgb(r,g,b));
		initImage();
		toolbar.setNavigationOnClickListener(this);
		tvToolbar.setText(UserName);
		collapsing.setTitle(UserName);
		tvDetailUserName.setText(UserName);
		//获取照片信息
		mApi.getUPhotosDetail(REQUEST_UPHOTOSDETAIL, PId);
	/*	Glide.with(PhotoDetailActivity.this).load(Background).asBitmap().into(new SimpleTarget<Bitmap>() {
			@Override
			public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
				bitmap = resource;
			}
		});*/
	}

	private void initImage() {
		//设置ImageView大小
		int width = SPUtils.getInstance().getInt("width");
		int height = SPUtils.getInstance().getInt("height");
		CollapsingToolbarLayout.LayoutParams params = new CollapsingToolbarLayout.LayoutParams(width,
				height);
		imageView.setLayoutParams(params);
		//加载大图
		Glide.with(PhotoDetailActivity.this).load(Background).diskCacheStrategy(DiskCacheStrategy.NONE).dontAnimate().into(imageView);
		//加载头像
		Glide.with(PhotoDetailActivity.this).load(ProfileImage).diskCacheStrategy(DiskCacheStrategy.ALL).dontAnimate().transform(new GlideCircleTransform(this)).into(imgDetailProfile);
	}

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 != -1) {
				switch (msg.what) {
					case REQUEST_UPHOTOSDETAIL:
						PhotoDetailsDTO dto = mGson.fromJson(msg.obj.toString(), PhotoDetailsDTO.class);
						String thumbUrl = dto.getUrls().getRegular();
						SPUtils.getInstance().put(ConstantValues.THUMB_URL,thumbUrl);
						tvDetailResolution.setText("Resolution：" + dto.getWidth() + "×" + dto.getHeight());
						if (dto.getExif().getExposure_time() != null) {
							tvShutter.setText("Exposure time：" + dto.getExif().getExposure_time());
						} else {
							tvShutter.setText("Exposure time：No information");
						}
						if (dto.getExif().getAperture() != null) {
							tvAperture.setText("Aperture：" + dto.getExif().getAperture());
						} else {
							tvAperture.setText("Aperture：No information");
						}
						if (dto.getExif().getFocal_length() != null) {
							tvFocus.setText("Focal length：" + dto.getExif().getFocal_length());
						} else {
							tvFocus.setText("Focal length：No information");
						}
						if (dto.getExif().getModel() != null) {
							tvEquipment.setText("Model：" + dto.getExif().getModel());
						} else {
							tvEquipment.setText("Model：No information");
						}
						if (dto.getExif().getIso() != null) {
							tvSpeed.setText("Iso：" + dto.getExif().getIso());
						} else {
							tvSpeed.setText("Iso：No information");
						}
						if (dto.getLocation() != null) {
							tvPlace.setText("Place：" + dto.getLocation().getName());
						} else {
							tvPlace.setText("Place：No information");
						}
						break;
					default:
						break;
				}
			}
		}
	};

	@Override
	public void onClick(View v) {
		supportFinishAfterTransition();
	}

	@OnClick({R.id.detail_download, R.id.detail_share, R.id.detail_wallpaper,R.id.imageView})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.detail_download:
				new QMUIDialog.MessageDialogBuilder(PhotoDetailActivity.this)
						.setMessage("Download this picture?")
						.addAction("no", new QMUIDialogAction.ActionListener() {
							@Override
							public void onClick(QMUIDialog dialog, int index) {
								dialog.dismiss();
							}
						})
						.addAction("yes", new QMUIDialogAction.ActionListener() {
							@Override
							public void onClick(QMUIDialog dialog, int index) {
								DownloadUtil.download(Background,PhotoDetailActivity.this);
								dialog.dismiss();
							}
						}).show();
				break;
			case R.id.detail_share:
				ShareUtils.shareByDownload(Background,PhotoDetailActivity.this);
				break;
			case R.id.detail_wallpaper:
				//设置背景
				startCrop();
				break;
			case R.id.imageView:
				if(!StringUtils.isEmpty(SPUtils.getInstance().getString(ConstantValues.THUMB_URL))){
					PhotoDialog photoDialog = new PhotoDialog();
					photoDialog.show(getFragmentManager(),"");
				}
				break;
		}
	}
	//开始裁剪
	private void startCrop() {
		Uri sourceUri = Uri.parse(Background);
		//裁剪后保存到文件中
		Uri destinationUri = Uri.fromFile(new File(getCacheDir(), "SampleCropBackground.jpeg"));
		UCrop.of(sourceUri, destinationUri).withAspectRatio(9, 16).withMaxResultSize(720, 1280).start(this);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
			final Uri resultUri = UCrop.getOutput(data);
			try {
				 mBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), resultUri);
			} catch (IOException e) {
				e.printStackTrace();
			}
			//设置桌面背景
			WallpaperManager manager = WallpaperManager.getInstance(this);
			try {
				manager.setBitmap(mBitmap);
				Toast.makeText(PhotoDetailActivity.this,"Set as wallpaper success",Toast.LENGTH_SHORT).show();
			} catch (IOException e) {
				e.printStackTrace();
				Toast.makeText(PhotoDetailActivity.this,"Setting failure",Toast.LENGTH_SHORT).show();
			}
		} else if (resultCode == UCrop.RESULT_ERROR) {
			final Throwable cropError = UCrop.getError(data);
		}
	}
}
